﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.TeamFoundation.VersionControl.Client;
using TfsComLib.TfsBranchLib2;

namespace TfsBranchLib2.View
{
    /// <summary>
    ///     Interaction logic for BranchedHistoryOutputControl.xaml
    /// </summary>
    public partial class BranchedHistoryOutputControl : UserControl
    {
        public delegate void ShowChangesetDetails(int changesetId);

        public class ChangesetDetailsEventArgs : EventArgs
        {
            public int ChangesetId { get; set; }
        }

        public static int MaxDetailsWindows = 25;
        private IBranchedHistory context;

        public BranchedHistoryOutputControl()
        {
            InitializeComponent();
        }

        internal void SetBindings(IBranchedHistory branchedHistoryContext)
        {
            context = branchedHistoryContext;
            historyGrid.SetBinding(ItemsControl.ItemsSourceProperty,
                new Binding("HistoryList") {Source = branchedHistoryContext});
        }

        private void CompareContextClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (OnCompare != null)
                {
                    if (historyGrid.SelectedItems.Count == 2)
                    {
                        var item1 = historyGrid.SelectedItems[0] as HistoryItem;
                        var item2 = historyGrid.SelectedItems[1] as HistoryItem;
                        if ((item1 == null) || (item2 == null))
                        {
                            return;
                        }
                        var path1 = item1.Branch.ServerPath + "/" + context.PathWithinBranches;
                        var path2 = item2.Branch.ServerPath + "/" + context.PathWithinBranches;
                        var vcs = context.SelectedBranchesCache.SourceBranchesProvider.VersionControlServer;
                        var isFilePath = (vcs.GetItem(path1, VersionSpec.Latest).ItemType == ItemType.File);
                        OnCompare(this, new CompareEventArgs
                        {
                            VersionControlServer =
                                context.SelectedBranchesCache.SourceBranchesProvider.TfsConnection.VersionControlServer,
                            isFile = isFilePath,
                            Path1 = path1,
                            Version1 = item1.ID,
                            Path2 = path2,
                            Version2 = item2.ID
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError("Compare Items", ex);
            }
        }

        private void ContextMenuOpened(object sender, RoutedEventArgs e)
        {
            compareContextItem.IsEnabled = ((historyGrid.SelectedItems.Count == 2) &&
                                            (context.QueryTypeResults == BranchedHistoryQueryType.SingleSubPath));
        }

        private void DetailsMenuItemClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (OnShowChangesetDetails != null)
                {
                    if (historyGrid.SelectedItems.Count > 0)
                    {
                        var i = 0;
                        foreach (HistoryItem item in historyGrid.SelectedItems)
                        {
                            OnShowChangesetDetails(this, new ChangesetDetailsEventArgs(){ ChangesetId = item.ID});
                            i++;
                            if (i > MaxDetailsWindows)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError("History Details", ex);
            }
        }

        /// <summary>
        ///     Когда пользователь выбирает посмотреть детали
        /// </summary>
        public event EventHandler<ChangesetDetailsEventArgs> OnShowChangesetDetails;

        public event EventHandler<CompareEventArgs> OnCompare;


        private void HistoryGridMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                var row =
                    ItemsControl.ContainerFromElement((DataGrid) sender, e.OriginalSource as DependencyObject) as
                        DataGridRow;
                // If so, go ahead and do my thing
                if (row != null)
                {
                    var item = row.Item as HistoryItem;
                    if ((item != null) && (OnShowChangesetDetails != null))
                    {
                        OnShowChangesetDetails(this, new ChangesetDetailsEventArgs() {ChangesetId = item.ID});
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError("History Grid Double Click", ex);
            }
        }

        /// <summary>
        ///     Show error
        /// </summary>
        /// <param name="p"></param>
        /// <param name="ex"></param>
        private void ShowError(string p, Exception ex)
        {
            context.ErrorMessage = string.Format("Status: {0}:{1}", p, ex.Message);
            context.IsError = true;
        }

        public class CompareEventArgs : EventArgs
        {
            public VersionControlServer VersionControlServer { get; set; }
            public string Path1 { get; set; }
            public int Version1 { get; set; }
            public string Path2 { get; set; }
            public int Version2 { get; set; }
            public bool isFile { get; set; }
        }
    }
}